package com.guiyang.practice.mess1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {

    public CorsConfig() {
        System.out.println("=== CORS配置已加载 ===");
    }

    /**
     * 创建CORS配置源
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        System.out.println("=== 创建CORS配置源 ===");

        CorsConfiguration configuration = new CorsConfiguration();

        // 允许的域名
        configuration.addAllowedOrigin("http://localhost:5173");
        configuration.addAllowedOrigin("http://127.0.0.1:5173");
        configuration.addAllowedOrigin("http://localhost:3000");

        // 允许的方法
        configuration.addAllowedMethod("GET");
        configuration.addAllowedMethod("POST");
        configuration.addAllowedMethod("PUT");
        configuration.addAllowedMethod("DELETE");
        configuration.addAllowedMethod("OPTIONS");
        configuration.addAllowedMethod("PATCH");

        // 允许的头部
        configuration.addAllowedHeader("*");

        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

    /**
     * 创建CORS过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        System.out.println("=== 创建CorsFilter Bean ===");
        return new CorsFilter(corsConfigurationSource());
    }
}